package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tutk.p2p.ConnectionEntity;

import java.util.ArrayList;
import java.util.List;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.customize.AddAutoPopupWindow;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.manager.SceneManager;
import cn.innosmart.aq.manager.ScheduleManager;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.AddActionActivity;
import cn.innosmart.aq.view.activity.RuleActivity;
import cn.innosmart.aq.view.activity.SceneActivity;

/**
 * Created by David on 2015/7/23.
 */
public class BoxDetailAutoFragment extends BaseFragment {

    private final int LOADINGOVER = 0;
    private final int SHOWADDPOPUPWINDOW = 1;
    private final int ADDRULE = 2;
    private final int ADDSCENCE = 3;
    private final int ADDSHCEDULE = 4;
    private final int MODIFYRULE = 5;
    private final int MODIFYSCENE = 6;
    private final int DATACHANGE = 7;
    private final int DELETESCENE = 8;
    private final int MODIFYSCHEDULE = 9;
    public boolean isModify = false;
    private Menu menus;
    //ViewPager
    private View view;
    private ViewPager mViewPager;
    //顶部三个LinearLayout
    private LinearLayout table1_column;
    private LinearLayout table2_column;
    private LinearLayout table3_column;
    //顶部三个TextView
    private TextView tv_table1;
    private TextView tv_table2;
    private TextView tv_table3;
    //TabLine
    private ImageView tab_line;
    /**
     * ViewPager的当前选中页
     */
    private int currentIndex;
    /**
     * 屏幕的宽度
     */
    private int screenWidth;
    private FragmentPagerAdapter mAdapter;
    private List<BaseFragment> mFragments = new ArrayList<BaseFragment>();
    /**
     * /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private String flag = "rule";
    private ConnectionEntity connectionEntity;
    //设置Popupwindow
    private AddAutoPopupWindow addAutoPopupWindow;
    private AquariumBean aquariumBean;
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            addAutoPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_add_rule:
                    //添加规则
                    mHandler.sendEmptyMessage(ADDRULE);
                    break;
                case R.id.btn_add_scene:
                    //添加场景
                    mHandler.sendEmptyMessage(ADDSCENCE);
                    break;
                case R.id.btn_add_schedule:
                    //添加排程
                    mHandler.sendEmptyMessage(ADDSHCEDULE);
                    break;
                case R.id.btn_cancel:
                    break;
            }
        }

    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOADINGOVER:
                    //加载结束
                    for (BaseFragment baseFragment : mFragments) {
                        baseFragment.refresh();
                    }
                    hideLoadingDialog();
                    break;
                case SHOWADDPOPUPWINDOW:
                    //显示添加弹出层
                    initMyPopupWindow();
                    break;
                case ADDRULE:
                    //添加规则
                    switchAddRule();
                    break;
                case ADDSCENCE:
                    //添加场景
                    switchAddScene();
                    break;
                case ADDSHCEDULE:
                    //添加排程
                    switchAddSchedule();
                    break;
                case DATACHANGE:
//                    刷新界面
                    onResume();
                    break;
                case MODIFYSCHEDULE:

                    break;


            }
        }


        /**
         * 添加排程
         */
        private void switchAddSchedule() {
            flag = "schedule";
            Intent intent = new Intent(getActivity(), AddActionActivity.class);
            intent.putExtra("flag", flag);
            ArrayList<String> actions = new ArrayList<String>();
            intent.putExtra("aquarium", aquariumBean.getId());
            System.out.println("actionss=" + aquariumBean);
            actions.addAll((ArrayList<String>) aquariumBean.getActionDevices().clone());
            intent.putStringArrayListExtra("actions", actions);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        }

        /**
         * 添加场景
         */
        private void switchAddScene() {
            flag = "scene";
            Intent intent = new Intent(getActivity(), SceneActivity.class);
            intent.putExtra("aquarium", aquariumBean.getId());
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        }

        /**
         * 添加规则
         */
        private void switchAddRule() {
            flag = "rule";
            Intent intent = new Intent(getActivity(), RuleActivity.class);
            intent.putExtra("aquarium", aquariumBean.getId());
            intent.putExtra("flag", flag);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        }


        private void switchModifyRule() {
            Intent intent = new Intent(getActivity(), RuleActivity.class);
            intent.putExtra("aquarium", aquariumBean);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        }
    };
    /**
     * 菜单点击事件监听
     */
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_edit_auto:
                    //编辑状态
                    isModify = !isModify;
                    for (BaseFragment baseFragment : mFragments) {
                        baseFragment.startModify(isModify);
                    }
                    if (isModify) {
                        menus.findItem(R.id.action_add_auto).setVisible(false);
                        menus.findItem(R.id.action_edit_auto).setTitle(R.string.action_exit_edit);
                    } else {
                        menus.findItem(R.id.action_add_auto).setVisible(true);
                        menus.findItem(R.id.action_edit_auto).setTitle(R.string.action_enter_edit);
                    }
                    break;
                case R.id.action_add_auto:
                    //添加
                    mHandler.sendEmptyMessage(SHOWADDPOPUPWINDOW);
                    break;
            }
            return true;
        }

    };

    //切换
    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.table1_column:
                    mViewPager.setCurrentItem(0);
                    break;
                case R.id.table2_column:
                    mViewPager.setCurrentItem(1);
                    break;
                case R.id.table3_column:
                    mViewPager.setCurrentItem(2);
                    break;
            }
        }
    };

    public AquariumBean getAquariumBean() {
        return aquariumBean;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_auto, container, false);
        setHasOptionsMenu(true);
        initComomnView(view);
        initTabLine(view);
        BoxDetailRuleFragment boxDetailRuleFragment = new BoxDetailRuleFragment();
        BoxDetailScheduleFragment boxDetailScheduleFragment = new BoxDetailScheduleFragment();
        BoxDetailSceneFragment boxDetailSceneFragment = new BoxDetailSceneFragment();
        mFragments.add(boxDetailRuleFragment);
        mFragments.add(boxDetailScheduleFragment);
        mFragments.add(boxDetailSceneFragment);
        /**
         * 初始化Adapter
         */
        mAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                return super.instantiateItem(container, position);
            }

            @Override
            public Parcelable saveState() {
                return super.saveState();
            }

            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
            }

            @Override
            public long getItemId(int position) {
                return super.getItemId(position);
            }

        };
        initListener();
        setBar();
        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initComomnView(View view) {
        table1_column = (LinearLayout) view.findViewById(R.id.table1_column);
        table1_column.setOnClickListener(mBtnOnClickListener);
        table2_column = (LinearLayout) view.findViewById(R.id.table2_column);
        table2_column.setOnClickListener(mBtnOnClickListener);
        table3_column = (LinearLayout) view.findViewById(R.id.table3_column);
        table3_column.setOnClickListener(mBtnOnClickListener);
        tv_table1 = (TextView) view.findViewById(R.id.tv_table1);
        tv_table2 = (TextView) view.findViewById(R.id.tv_table2);
        tv_table3 = (TextView) view.findViewById(R.id.tv_table3);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
        tv_table1.setText(R.string.fragment_auto_rule);
        tv_table2.setText(R.string.fragment_auto_schedule);
        tv_table3.setText(R.string.fragment_auto_scene);
    }

    private void initListener() {
        mViewPager.setAdapter(mAdapter);
        /**
         * 设置监听
         */
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 重置所有TextView的字体颜色
                resetTextView();
                switch (position) {
                    case 0:
                        tv_table1.setTextColor(getResources().getColor(R.color.font_lightblue));
                        break;
                    case 1:
                        tv_table2.setTextColor(getResources().getColor(R.color.font_lightblue));
                        break;
                    case 2:
                        tv_table3.setTextColor(getResources().getColor(R.color.font_lightblue));
                        break;
                }

                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                /**
                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
                 */
                if (currentIndex == 0 && position == 0)// 0->1
                {
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tab_line.getLayoutParams();
                    lp.leftMargin = (int) (positionOffset * (screenWidth * 1.0 / 3) + currentIndex * (screenWidth / 3));
                    tab_line.setLayoutParams(lp);

                } else if (currentIndex == 1 && position == 0) // 1->0
                {
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tab_line.getLayoutParams();
                    lp.leftMargin = (int) (-(1 - positionOffset) * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    tab_line.setLayoutParams(lp);

                } else if (currentIndex == 1 && position == 1) // 1->2
                {
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tab_line.getLayoutParams();
                    lp.leftMargin = (int) (positionOffset * (screenWidth * 1.0 / 3) + currentIndex * (screenWidth / 3));
                    tab_line.setLayoutParams(lp);
                } else if (currentIndex == 2 && position == 1) // 2->1
                {
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tab_line.getLayoutParams();
                    lp.leftMargin = (int) (-(1 - positionOffset) * (screenWidth * 1.0 / 3) + currentIndex
                            * (screenWidth / 3));
                    tab_line.setLayoutParams(lp);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(0);
        tv_table1.setTextColor(getResources().getColor(R.color.font_lightblue));
    }

    /**
     * 重置颜色
     */
    protected void resetTextView() {
        tv_table1.setTextColor(getResources().getColor(R.color.white));
        tv_table2.setTextColor(getResources().getColor(R.color.white));
        tv_table3.setTextColor(getResources().getColor(R.color.white));
    }

    /**
     * 根据屏幕的宽度，初始化引导线的宽度
     */
    private void initTabLine(View view) {
        tab_line = (ImageView) view.findViewById(R.id.tab_line);
        DisplayMetrics outMetrics = new DisplayMetrics();
        getActivity().getWindow().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        screenWidth = outMetrics.widthPixels;
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tab_line.getLayoutParams();
        lp.width = screenWidth / 3;
        tab_line.setLayoutParams(lp);
    }


    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_auto, menu);
        menus = menu;
//        menus.getItem(0).setTitle()
        super.onCreateOptionsMenu(menu, inflater);
    }

    public void setConnectionEntity(ConnectionEntity connectionEntity) {
        this.connectionEntity = connectionEntity;
    }


    /**
     * 读取自动控制的数据 规则 排程 场景
     */
    private void getData() {
        if (SystemConstant.scheduleList == null || SystemConstant.sceneList == null) {
            showLoadingDialog(getActivity());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SceneManager.getInstance().List(connectionEntity, new SceneManager.ListCallBack() {
                        @Override
                        public void onListResponseCallBack(int ret, ArrayList<Object> childList) {
                            if (ret == 0) {
                                SystemConstant.sceneList = childList;
                                System.out.println("");
                            }

                        }
                    }, 10);
                    ScheduleManager.getInstance().List(connectionEntity, new ScheduleManager.ListCallBack() {
                        @Override
                        public void onListResponseCallBack(int ret, ArrayList<Object> childList) {
                            if (ret == 0) {
                                SystemConstant.scheduleList = childList;
                            }
                        }
                    }, 20);
                    RuleManager.getInstance().List(connectionEntity, new RuleManager.ListCallBack() {
                        @Override
                        public void onListResponseCallBack(int ret, ArrayList<Object> childList) {
                            if (ret == 0) {
                                SystemConstant.ruleList = childList;
                            }
                            mHandler.sendEmptyMessage(LOADINGOVER);
                        }
                    }, 30);
                }
            }).start();
        } else {
            mHandler.sendEmptyMessage(LOADINGOVER);
        }
    }


    @Override
    public void onResume() {
        getData();
        super.onResume();
    }

    private void initMyPopupWindow() {
        addAutoPopupWindow = new AddAutoPopupWindow(getActivity(), itemsOnClick);
        addAutoPopupWindow.showAtLocation(getActivity().findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void setAquarium(AquariumBean aquarium) {
        this.aquariumBean = aquarium;
    }


    /**
     * 刷新各个UI界面
     */
    public void refresh() {
        for (BaseFragment baseFragment : mFragments) {
            baseFragment.refresh();
        }
    }
}
